/**
 * https://www.bilibili.com/video/BV1Mb411e7re?p=27
 * AT24C02 / AT24C02N, 几毛钱1个
 * 是一种可以实现掉电不丢失的存储器，可用于保存单片机运行时想要永久保存的数据信息
 * 存储介质：E2PROM (Electrically Erasable Programmable Read Only Memory)
 * 通讯接口：I2C总线
 * 容量：256字节
 * 
 * https://www.bilibili.com/video/BV1Mb411e7re?p=28
 */
#include <REGX52.H>
#include "Link/Single_Keyboard_Utils.h"
#include "Link/Timer0_Utils.h"
#include "Link/AT24C02_Utils.h"
#include "Link/UART_Utils.h"

static void Write_and_Read();

static unsigned char Data;

static void Timer0_onTick() {
    static unsigned char T0Count1;
    T0Count1 ++;
    //每15ms调用1次
    if (T0Count1 >= 15) {
        T0Count1 = 0;
        Single_Keyboard_Down_Timer(1);
    }
}

void main_at24c02_1() {
    unsigned char KeyNum;
    UART_Init(0, 4800);
    UART_sendString("AT24C02: Store, Use UART_send!!!", 1);
    
    //1.写&读
    // Write_and_Read();
    // while (1);

    //2.根据按键 加&减&写&读 操作 (独立键盘 与 LCD 引脚有冲突, ∴用UART)
    UART_sendStringFormat(1, "Data = %bu", Data);
    Timer0_Init(1000, 0);
    Timer0_setOnTickListener_Exact(1, &Timer0_onTick);
    while (1) {
        //根据独立按键, 操作读写存储
        KeyNum = Single_Keyboard_Down_Timer_Get();
        switch (KeyNum) {
            case 1: Data++; UART_sendStringFormat(1, "Data = %bu", Data); break;
            case 2: Data--; UART_sendStringFormat(1, "Data = %bu", Data); break;
            case 3: AT24C02_WriteByte(0, Data, 0); UART_sendStringFormat(1, "Write Ok, Data = %bu", Data); break;
            case 4: Data = AT24C02_ReadByte(0); UART_sendStringFormat(1, "Read Ok, Data = %bu", Data); break;
            default: break;
        }
    }
}

//1.写&读
static void Write_and_Read() {
    //写3个字节
    AT24C02_WriteByte(0, 123, 1);
    AT24C02_WriteByte(1, 66, 1);
    AT24C02_WriteByte(3, 23, 1);

    //读1个字节
    Data = AT24C02_ReadByte(1); //66
    UART_sendStringFormat("1, Data = %bu", Data);
}